package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.fremework.BaseController;
import cn.stylefeng.guns.fremework.LayuiPageFactory;
import cn.stylefeng.guns.fremework.ResponseData;
import cn.stylefeng.guns.modular.system.entity.SysDept;
import cn.stylefeng.guns.modular.system.entity.SysRole;
import cn.stylefeng.guns.modular.system.entity.User;
import cn.stylefeng.guns.modular.system.factory.UserFactory;
import cn.stylefeng.guns.modular.system.model.UserDto;
import cn.stylefeng.guns.modular.system.service.SysDeptService;
import cn.stylefeng.guns.modular.system.service.SysRoleService;
import cn.stylefeng.guns.modular.system.service.UserService;
import cn.stylefeng.guns.modular.system.warpper.UserWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/mgr")
public class UserMgrController extends BaseController {

    private static String PREFIX = "/modular/system/user/";

    @Autowired
    private UserService userService;

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysRoleService roleService;

    /**
     * 跳转到查看管理员列表的页面
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:43
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "user.html";
    }


    @ResponseBody
    @RequestMapping("/page")
    public ResponseData page(Page page, User params) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(params.getName())){
            queryWrapper.and(wrapper -> wrapper.like(User::getName, params.getName()));
        }
        IPage result = userService.page(page, queryWrapper);
        return ResponseData.success(result);
    }
    /**
     * 跳转到查看管理员列表的页面
     */
    @RequestMapping("/user_add")
    public String addView() {
        return PREFIX + "user_add.html";
    }

    /**
     * 跳转到角色分配页面
     */
    @RequestMapping("/role_assign")
    public String roleAssign(@RequestParam Long userId, Model model) {
        model.addAttribute("userId", userId);
        return PREFIX + "user_roleassign.html";
    }

    /**
     * 跳转到编辑管理员页面
     */
    @RequestMapping("/user_edit")
    public String userEdit(@RequestParam Long userId) {
        User user = this.userService.getById(userId);
        return PREFIX + "user_edit.html";
    }

    /**
     * 获取用户详情
     */
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public Object getUserInfo(@RequestParam Long userId) {
        this.userService.assertAuth(userId);
        User user = this.userService.getById(userId);
        Map<String, Object> map = UserFactory.removeUnSafeFields(user);
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.putAll(map);
        SysRole sysRole = roleService.getById(user.getRoleId());
        SysDept sysDept = deptService.getById(user.getDeptId());
        hashMap.put("roleName", sysRole.getName());
        hashMap.put("deptName", sysDept.getSimpleName());

        return ResponseData.success(hashMap);
    }


    @ResponseBody
    @RequestMapping("/changePwd")
    public Object changePwd(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        this.userService.changePwd(oldPassword, newPassword);
        return ResponseData.success();
    }


    /**
     * 查询管理员列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String name,
                       @RequestParam(required = false) String timeLimit,
                       @RequestParam(required = false) Long deptId) {

        //拼接查询条件
        String beginTime = "";
        String endTime = "";

        if (!StringUtils.isEmpty(timeLimit)) {
            String[] split = timeLimit.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }

        Page<Map<String, Object>> users = userService.selectUsers( name, beginTime, endTime, deptId);
        Page wrapped = new UserWrapper(users).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);
    }

    /**
     * 添加管理员
     */
    @RequestMapping("/add")
    @ResponseBody
    public ResponseData add(@Valid UserDto user, BindingResult result) {
        this.userService.addUser(user);
        return ResponseData.success();
    }

    /**
     * 修改管理员
     */
    @RequestMapping("/edit")
    @ResponseBody
    public ResponseData edit(@Valid UserDto user, BindingResult result) {
        this.userService.editUser(user);
        return ResponseData.success();
    }

    /**
     * 删除管理员（逻辑删除）
     */

    @ResponseBody
    @RequestMapping("/delete")
    public ResponseData delete(@RequestParam Long userId) {
        this.userService.deleteUser(userId);
        return ResponseData.success();
    }

    /**
     * 查看管理员详情
     */
    @ResponseBody
    @RequestMapping("/view/{userId}")
    public User view(@PathVariable Long userId) {
        this.userService.assertAuth(userId);
        return this.userService.getById(userId);
    }


    /**
     * 冻结用户
     */
    @ResponseBody
    @RequestMapping("/freeze")
    public ResponseData freeze(@RequestParam Long userId) {
        this.userService.assertAuth(userId);
        this.userService.setStatus(userId, "LOCKED");
        return ResponseData.success();
    }

    /**
     * 解除冻结用户
     */
    @ResponseBody
    @RequestMapping("/unfreeze")
    public ResponseData unfreeze(@RequestParam Long userId) {
        this.userService.assertAuth(userId);
        this.userService.setStatus(userId, "ENABLE");
        return ResponseData.success();
    }

    /**
     * 分配角色
     */
    @ResponseBody
    @RequestMapping("/setRole")
    public ResponseData setRole(@RequestParam("userId") Long userId, @RequestParam("roleIds") String roleIds) {
        this.userService.assertAuth(userId);
        this.userService.setRoles(userId, roleIds);
        return ResponseData.success();
    }

}
